<template>
  <div class="edit-photo">
    <img class="img" :src="img" ref="img" />
    <div class="toobar">
      <div class="canvel" @click="$emit('close')">取消</div>
      <div class="confirm" @click="onSetPhoto">完成</div>
    </div>
  </div>
</template>

<script>
import 'cropperjs/dist/cropper.css'
import Cropper from 'cropperjs'
import { editUserPhoto } from '@/api/users'
export default {
  name: 'EditPhoto',
  props: {
    img: {
      type: [String, Object],
      require: true
    }
  },
  data () {
    return {
      cropper: null
    }
  },
  mounted () {
    const image = this.$refs.img
    this.cropper = new Cropper(image, {
      viewMode: 1,
      dragMode: 'move',
      aspectRatio: 1,
      autoCropArea: 1,
      cropBoxMovable: false,
      cropBoxResizable: false,
      background: false,
      movable: true
    })
    console.log(this.cropper)
  },
  methods: {
    onSetPhoto () {
      this.cropper.getCroppedCanvas().toBlob((blob) => {
        this.setPhoto(blob)
      })
    },
    async setPhoto (blob) {
      this.$toast.loading({
        message: '保存中....',
        forbidClick: true,
        duration: 0
      })
      try {
        const formData = new FormData()
        formData.append('photo', blob)
        const { data } = await editUserPhoto(formData)
        this.$emit('close')
        this.$emit('edit-photo', data.data.photo)
      } catch (err) {
        this.$toast('修改头像失败')
      }
    }
  }
}
</script>

<style lang="less" scoped>
.edit-photo {
  background-color: #000;
  height: 100%;
  .img {
    min-width: 100%;
    max-width: 100%;
    display: block;
  }
  .toobar {
    position: fixed;
    left: 0;
    right: 0;
    bottom: 0;
    display: flex;
    justify-content: space-between;
    .canvel,
    .confirm {
      width: 90px;
      height: 90px;
      font-size: 30px;
      display: flex;
      justify-content: center;
      align-content: center;
      line-height: 90px;
      color: #fff;
    }
  }
}
</style>
